#!/usr/bin/env python3
"""
运行Stage2测试，验证增强后的Key Features提取
"""

import subprocess
import sys
import json
import os

def run_stage2_test():
    """运行Stage2测试"""
    
    print("🚀 开始运行Stage2测试，验证增强后的Key Features提取...")
    
    # 检查是否存在必要的文件
    files_to_check = [
        "main.py",
        "src/model_scraper.py", 
        "fetchNgc2.json"
    ]
    
    for file_path in files_to_check:
        if not os.path.exists(file_path):
            print(f"❌ 缺少必要文件: {file_path}")
            return False
    
    try:
        # 构建命令
        cmd = [sys.executable, "main.py"]
        
        print(f"📋 执行命令: {' '.join(cmd)}")
        print("⏳ 开始执行抓取...")
        
        # 执行命令
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=300  # 5分钟超时
        )
        
        print(f"📊 执行结果:")
        print(f"  返回码: {result.returncode}")
        print(f"  标准输出长度: {len(result.stdout)} 字符")
        print(f"  错误输出长度: {len(result.stderr)} 字符")
        
        if result.stdout:
            print(f"\n📝 标准输出:")
            # 只显示最后几行
            lines = result.stdout.split('\n')
            for line in lines[-20:]:
                if line.strip():
                    print(f"    {line}")
        
        if result.stderr:
            print(f"\n❌ 错误输出:")
            lines = result.stderr.split('\n')
            for line in lines[-10:]:
                if line.strip():
                    print(f"    {line}")
        
        return result.returncode == 0
        
    except subprocess.TimeoutExpired:
        print("⏰ 执行超时（5分钟）")
        return False
    except Exception as e:
        print(f"❌ 执行失败: {e}")
        return False

def analyze_results():
    """分析抓取结果"""
    
    print("\n🔍 分析抓取结果...")
    
    try:
        # 检查输出文件
        output_files = ["./release/output.json", "./release/optimized_output.json"]
        
        for file_path in output_files:
            if os.path.exists(file_path):
                print(f"\n📁 分析文件: {file_path}")
                
                with open(file_path, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                if "car_objects" in data:
                    car_objects = data["car_objects"]
                    
                    print(f"  📊 找到 {len(car_objects)} 个车型")
                    
                    for car_obj in car_objects:
                        model_name = car_obj.get("model_name", "Unknown")
                        key_features = car_obj.get("key_features", [])
                        
                        print(f"\n  🚗 {model_name}:")
                        print(f"    特性数量: {len(key_features)}")
                        
                        # 检查是否还有导航菜单项
                        nav_items = ['Bodystyle', 'Colour', 'Interior', 'Extras', 'Summary']
                        nav_count = sum(1 for item in key_features if item in nav_items)
                        feature_count = len(key_features) - nav_count
                        
                        print(f"    导航菜单项: {nav_count}")
                        print(f"    真实特性: {feature_count}")
                        
                        # 显示前几个特性
                        real_features = [f for f in key_features if f not in nav_items]
                        for i, feature in enumerate(real_features[:3]):
                            print(f"      {i+1}. {feature}")
                        
                        if len(real_features) > 3:
                            print(f"      ... 还有 {len(real_features) - 3} 个特性")
            else:
                print(f"❌ 文件不存在: {file_path}")
        
    except Exception as e:
        print(f"❌ 分析结果失败: {e}")

def main():
    """主函数"""
    
    # 运行Stage2测试
    success = run_stage2_test()
    
    if success:
        print("\n✅ Stage2执行成功")
    else:
        print("\n❌ Stage2执行失败")
    
    # 分析结果
    analyze_results()
    
    print("\n🎯 测试总结:")
    if success:
        print("✅ 增强后的Key Features提取系统已成功集成")
        print("🔍 请检查上述分析结果，确认特性数量和质量是否符合预期")
    else:
        print("❌ 系统执行出现问题，请检查错误信息")

if __name__ == "__main__":
    main()
